import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { Message } from 'element-ui'
import Storage from '@/utils/storage'
import { Foundation } from '~/ui-utils'

const whiteList = ['/login', '/franchise/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  const refreshToken = Storage.getItem('admin_refresh_token')
  if (refreshToken) {
    if ((to.path === '/login' || to.path === '/franchise/login') && store.getters.addRouters.length) {
      Foundation.toFirstRoute(router, next)
      NProgress.done()
    } else {
      if (store.getters.addRouters.length === 0) {
        store.dispatch('GenerateRoutes').then(() => {
          const routers = store.getters.addRouters
          router.addRoutes(routers)
          if (routers.length) {
            const paths = router.getRoutes().map(item => item.path)
            if (paths.includes(to.path)) {
              next({ ...to, replace: true })
            } else {
              Foundation.toFirstRoute(router, next)
            }
          } else {
            next('/404')
          }
        }).catch(() => {
          store.dispatch('fedLogoutAction').then(() => {
            Message.error('验证失败,请重新登录')
            let to = Storage.getItem('admin_franchise') ? '/franchise/login' : '/login'
            window.location.replace(router.resolve(to).href)
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      let to = Storage.getItem('admin_franchise') ? '/franchise/login' : '/login'
      next(to)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
